﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.UI.WebControls;

using umbraco;
using umbraco.BasePages;
using umbraco.uicontrols;

namespace CodeGecko.Modules.Umbraco.AppCodeEditor
{
	public partial class editCodeFile : UmbracoEnsuredPage
	{
		protected override void OnInit(EventArgs e) {
			ImageButton button = this.Panel1.Menu.NewImageButton();
			button.Click += new ImageClickEventHandler(this.Save_Click);
			button.AlternateText = "Save Code File";
			button.ImageUrl = String.Concat(GlobalSettings.Path, "/images/editor/save.gif");

			base.Load += new EventHandler(this.Page_Load);
			base.OnInit(e);
		}

		protected void Page_Load(Object sender, EventArgs e) {
			String fileName = base.Request.QueryString["file"].Replace(@"/", @"\");
            String applicationPath = GlobalSettings.FullpathToRoot;
			if (applicationPath == "/")
				applicationPath = String.Empty;

			this.lttPath.Text = String.Concat(applicationPath.Substring(0, applicationPath.Length - 1), fileName);

			if (!base.IsPostBack) {
				using (StreamReader reader = File.OpenText(base.Server.MapPath(fileName))) {
					String contents = reader.ReadToEnd();

					if (!String.IsNullOrEmpty(contents)) this.editorSource.Text = contents;
				}
			}

			this.Panel1.Text = "Edit Code File";
			this.pp_path.Text = "Path";
		}

		private void Save_Click(Object sender, ImageClickEventArgs e) {
			if (this.SaveUserControlFile(this.lttPath.Text, base.Request.QueryString["file"], this.editorSource.Text)) {
				base.speechBubble(BasePage.speechBubbleIcon.save, ui.Text("speechBubbles", "fileSavedHeader"), String.Empty);
			} else {
				base.speechBubble(BasePage.speechBubbleIcon.save, ui.Text("speechBubbles", "fileErrorHeader"), ui.Text("speechBubbles", "fileErrorText"));
			}
		}

		public bool SaveUserControlFile(String filename, String oldName, String contents) {
            try {
                //Try and compile
                using (StreamWriter writer = File.CreateText(filename)) {
					writer.Write(contents);
				}
                if (!filename.EndsWith(".ascx") && !filename.Contains("usercontrols")) {
                    Assembly appCodeFile = BuildManager.GetCompiledAssembly(filename);
                }
                if ((filename != oldName) && File.Exists(base.Server.MapPath(oldName))) {
					File.Delete(base.Server.MapPath(oldName));
				}
                return true;
            } catch (Exception ex) {
                //Throw
				return false;
			}
		}
	}
}
